package com.yuelao.yuelao_backend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yuelao.yuelao_backend.common.BizException;
import com.yuelao.yuelao_backend.common.ErrorCode;
import com.yuelao.yuelao_backend.dto.MessageDTO;
import com.yuelao.yuelao_backend.entity.Group;
import com.yuelao.yuelao_backend.entity.GroupMessage;
import com.yuelao.yuelao_backend.entity.User;
import com.yuelao.yuelao_backend.mapper.GroupMapper;
import com.yuelao.yuelao_backend.mapper.GroupMessageMapper;
import com.yuelao.yuelao_backend.mapper.UserMapper;
import com.yuelao.yuelao_backend.service.AchievementService;
import com.yuelao.yuelao_backend.service.GroupMessageService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import jakarta.annotation.Resource;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 群聊消息Service实现类
 * 重构说明：新增，用于处理群聊消息
 */
@Service
public class GroupMessageServiceImpl extends ServiceImpl<GroupMessageMapper, GroupMessage> implements GroupMessageService {

    @Resource
    private UserMapper userMapper;
    
    @Resource
    private GroupMapper groupMapper;
    
    @Resource
    private AchievementService achievementService;

    @Override
    public List<MessageDTO> getGroupChatHistory(Long groupId, int pageNum, int pageSize) {
        // 检查群聊是否存在
        Group group = groupMapper.selectById(groupId);
        if (group == null) {
            throw new BizException(ErrorCode.NOT_FOUND_ERROR, "群聊不存在");
        }

        Page<GroupMessage> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<GroupMessage> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(GroupMessage::getGroupId, groupId)
                    .eq(GroupMessage::getIsRevoked, false)
                    .orderByDesc(GroupMessage::getCreatedAt);

        Page<GroupMessage> messagePage = page(page, queryWrapper);
        return messagePage.getRecords().stream()
                .map(this::convertToMessageDTO)
                .collect(Collectors.toList());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean sendGroupMessage(Long senderId, Long groupId, String messageType,
                                   String content, String mediaUrl) {
        // 检查发送者和群聊是否存在
        User sender = userMapper.selectById(senderId);
        Group group = groupMapper.selectById(groupId);
        if (sender == null || group == null) {
            throw new BizException(ErrorCode.NOT_FOUND_ERROR, "发送者或群聊不存在");
        }

        // 检查群是否已解散
        if (group.getStatus() != null && group.getStatus() == 0) {
            throw new BizException(ErrorCode.OPERATION_ERROR, "群聊已解散");
        }

        // TODO: 检查是否是群成员
        // TODO: 检查是否被禁言

        GroupMessage message = new GroupMessage();
        message.setGroupId(groupId);
        message.setSenderId(senderId);
        message.setMessageType(messageType);
        message.setContent(content);
        message.setMediaUrl(mediaUrl);
        message.setIsRevoked(false);
        message.setCreatedAt(LocalDateTime.now());

        boolean saved = save(message);
        
        // 检查群消息相关成就
        if (saved) {
            achievementService.checkMessageAchievements(senderId, true);
        }
        
        return saved;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean revokeGroupMessage(Long messageId, Long userId) {
        GroupMessage message = getById(messageId);
        if (message == null) {
            throw new BizException(ErrorCode.NOT_FOUND_ERROR, "消息不存在");
        }

        // 检查权限：发送者或群主可以撤回
        Group group = groupMapper.selectById(message.getGroupId());
        if (group == null) {
            throw new BizException(ErrorCode.NOT_FOUND_ERROR, "群聊不存在");
        }

        boolean canRevoke = message.getSenderId().equals(userId) || group.getOwnerId().equals(userId);
        if (!canRevoke) {
            throw new BizException(ErrorCode.NO_AUTH_ERROR, "只有发送者或群主才能撤回消息");
        }

        // 检查是否超过2分钟（群主不受此限制）
        if (!group.getOwnerId().equals(userId) &&
            message.getCreatedAt() != null &&
            LocalDateTime.now().isAfter(message.getCreatedAt().plusMinutes(2))) {
            throw new BizException(ErrorCode.OPERATION_ERROR, "超过2分钟的消息无法撤回");
        }

        message.setIsRevoked(true);
        message.setRevokedAt(LocalDateTime.now());
        return updateById(message);
    }

    @Override
    public MessageDTO convertToMessageDTO(GroupMessage groupMessage) {
        if (groupMessage == null) {
            return null;
        }
        MessageDTO dto = new MessageDTO();
        BeanUtils.copyProperties(groupMessage, dto);

        // 手动设置创建时间
        dto.setSentAt(groupMessage.getCreatedAt());

        // 填充发送者昵称和头像
        User sender = userMapper.selectById(groupMessage.getSenderId());
        if (sender != null) {
            dto.setSenderNickname(sender.getNickname());
            dto.setSenderAvatar(sender.getAvatar());
        }

        // 填充群名称
        Group group = groupMapper.selectById(groupMessage.getGroupId());
        if (group != null) {
            dto.setGroupName(group.getName());
        }

        return dto;
    }
}

